import Vue from 'vue'
import Router from 'vue-router'
import ErrPage from '../components/error/error404';
import ViewUI from 'view-design';
Vue.use(ViewUI);

const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error)
}

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/layout',
      component: resolve => require(['../components/layout/index.vue'], resolve),
      children: [{
        path: "/dashboard",
        component: resolve => require(['@/components/views/dashboard/index'], resolve)
      }]
    },
    {
      path: '/login',
      component: resolve => require(['../components/login/index.vue'], resolve)
    },
    {
      path: '/error404',
      component: ErrPage
    },
    { //重定向到404
      path: '*', redirect: '/error404'
    }
  ]
})

//刷新
router.beforeEach((to, from, next) => {
  if (localStorage.getItem('menus')) {
    if (getLastUrl(window.location.href, '/') == to.redirectedFrom && to.redirectedFrom != '/') {
      let menus = JSON.parse(localStorage.getItem('menus'))
      let rs = routes(menus)
      router.addRoutes(rs)
      router.replace(to.redirectedFrom)
    }
  }
  ViewUI.LoadingBar.start();
  next()
})

router.afterEach(route => {
  ViewUI.LoadingBar.finish();
});

/**
 * 取上一个链接
 *
 * @param str
 * @param yourStr
 * @returns {*}
 */
let getLastUrl = (str, yourStr) => str.slice(str.lastIndexOf(yourStr))

/**
 * 取路由列表
 *
 * @param menuArray
 * @returns {*[]}
 */
let routes = (menuArray) => {
  let routes = [{
    path: '/layout',
    component: resolve => require(['@/components/layout/index.vue'], resolve),
    children: [{
      path: "/dashboard",
      component: resolve => require(['@/components/views/dashboard/index'], resolve)
    }]
  }]
  if (menuArray) {
    for (let index = 0; index < menuArray.length; index++) {
      const menu = menuArray[index]
      if (menu.viewPath) {
        let route = {
          path: menu.url,
          component: resolve => require(['@/components/views' + menu.viewPath], resolve)
        };
        routes[0].children.push(route)
      }
    }
  }
  return routes
}

export default router
